package org.study.r2dbc.boot.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.study.r2dbc.boot.model.User;
import org.study.r2dbc.boot.service.UserServiceByEntityTemplate;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年04月02日
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("/api/user/entityTemplate")
public class UserEntityTemplateController {
    private final UserServiceByEntityTemplate userServiceByEntityTemplate;

    @GetMapping("/active")
    public Flux<User> findActiveUsers() {
        return userServiceByEntityTemplate.findActiveUsers();
    }

    @GetMapping("/condition")
    public Flux<User> findActiveUsers(@RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "active", required = false) Boolean active) {
        return userServiceByEntityTemplate.findUsers(name, active);
    }

    @PostMapping("/saveUser1")
    @ResponseStatus(HttpStatus.CREATED)
    public Mono<User> saveUser1(@RequestBody User user) {
        return userServiceByEntityTemplate.saveUser1(user);
    }

    @PostMapping("/saveUser2")
    @ResponseStatus(HttpStatus.CREATED)
    public Mono<User> saveUser2(@RequestBody User user) {
        return userServiceByEntityTemplate.saveUser2(user);
    }

    @PostMapping("/saveUser3")
    @ResponseStatus(HttpStatus.CREATED)
    public Mono<ResponseEntity<Map<String, Object>>> saveUser3(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>() {{
            this.put("timestamp", Instant.now());
        }};
        return userServiceByEntityTemplate.saveUser3(user)
                .map(savedUser -> {
                    map.put("code", "0000");
                    map.put("status", "success");
                    map.put("msg", "保存成功");
                    map.put("data", savedUser);
                    return ResponseEntity.status(HttpStatus.CREATED).body(map);
                })
                .onErrorResume(ex -> {
                    map.put("code", "9999");
                    map.put("status", "fail");
                    map.put("msg", "保存失败");
                    map.put("data", null);
                    map.put("error", ex.getMessage());
                    return Mono.just(ResponseEntity.badRequest().body(map));
                });
    }
}
